package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 订单任务类, 处理订单状态
 */
@Component
@Slf4j
public class OrderTask {
  
  private final OrderMapper orderMapper;
  
  public OrderTask(OrderMapper orderMapper) {
    this.orderMapper = orderMapper;
  }
  
  /**
   * 处理超时未支付订单
   * 每分钟触发一次
   */
  // @Scheduled(cron = "0 * * * * ?")
  public void processTimeoutOrder() {
    log.info("定时处理超时订单，{}", LocalDateTime.now());
    
    // 当前时间 减去 15分钟
    LocalDateTime time = LocalDateTime.now().minusMinutes(15);
    // 查询所有超时的订单
    List<Orders> ordersList = orderMapper.getTimeoutOrders(Orders.PENDING_PAYMENT, time);
    
    if(ordersList != null && !ordersList.isEmpty()) {
      for (Orders orders : ordersList) {
        orders.setStatus(Orders.CANCELLED); // 修改订单状态为 已取消
        orders.setCancelReason("订单超时未支付~");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders); // 更新订单数据
      }
    }
  }
  
  /**
   * 定时处理 派送订单已完成
   * 每天凌晨1点触发
   */
  @Scheduled(cron = "0 0 1 * * ?")
  public void processDeliveryOrder() {
    log.info("定时处理派送中订单: {}", LocalDateTime.now());
    // 查询所有派送中的订单id
    List<Long> orderIds = orderMapper.getDeliverOrderIds(Orders.DELIVERY_IN_PROGRESS);
    if(orderIds != null && !orderIds.isEmpty()) {
      // 批量修改所有派送订单为已完成
      orderMapper.batchUpdateStatus(orderIds, Orders.COMPLETED);
    }
  
  }
}
